<template>
    <j-modal
      width="100%"
      title="合同管理"
      :maskClosable="false"
      :fullscreen.sync="fullscreen"
      :switch-fullscreen="switchFullscreen"
      :destroyOnClose="true"
      :visible.sync="editModalVisible"
      @cancel="handleCancleDbSync"
      :bodyStyle="{paddingTop:'0px'}"
    >
    <template slot="footer">
      <div style="text-align:center;">
        <a-button @click="handleCancleDbSync">关闭</a-button>
        <a-button type="primary" v-if="currentSteps === 0" @click="handlePre">下一步</a-button>
        <a-button type="primary" v-if="currentSteps === 1" ghost @click="handlePre">上一步</a-button>
        <!-- <a-button type="primary" v-if="currentSteps === 1" @click="handlePayPlan">生成还款计划</a-button> -->
        <a-button type="primary"  v-if="currentSteps === 1" :loading="syncLoading" @click="handleDbSync">保存</a-button>
      </div>
    </template>
    <div class="table-page-search-wrapper warp" v-if="editModalVisible">
      <a-steps type="navigation" size="small" :current="currentSteps" style="margin-bottom:20px;">
        <a-step title="填写基础信息"></a-step>
        <a-step title="填写费项信息"/>
      </a-steps>
      <!-- 合同基本信息 -->
      <a-form-model v-show="currentSteps === 0" layout="horizontal" labelAlign="right" ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol" :model="formData" :rules="rules">
        <a-row :gutter="24">
          <a-col :xl="8" :lg="8" :md="8" :sm="24" >
            <a-form-model-item label="合同编码" prop="contractCode">
              <a-input disabled v-model="formData.contractCode" placeholder="请输入合同编码"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24">
            <a-form-model-item label="合同类型" prop="contractType">
              <j-dict-select-tag
                v-model="formData.contractType"
                placeholder="请选择"
                disabled
                dict-code="xy_park_contract_type"
              >
              </j-dict-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" >
            <a-form-model-item label="跟进人" prop="bizUser">
              <j-select-multi-user :multiple="false" v-model="formData.bizUser" />
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" >
            <a-form-model-item label="合同签订日期" prop="contractDate">
              <a-date-picker style="width:100%;" placeholder="请输入备注" v-model="formData.contractDate" />
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" >
            <a-form-model-item label="收款账户" prop="account">
              <j-popup
                v-model="formData.account"
                org-fields="park_number,company,deposit_park"
                dest-fields="account,company,depositPark"
                field="account"
                code="v_xy_park_account"
                :trigger-change="true"
                @callback="popCallbackAccount"
              />
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" >
            <a-form-model-item label="收款公司">
              <a-input style="width:100%;" disabled :value="formData.xyParkAccount && formData.xyParkAccount.company" />
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" >
            <a-form-model-item label="开户行">
              <a-input style="width:100%;" disabled :value="formData.xyParkAccount && formData.xyParkAccount.depositPark" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">乙方</a-divider>
        <a-row :gutter="24">
          <a-col :xl="8" :lg="8" :md="8" :sm="24" >
            <a-form-model-item label="客户名称" prop="ownerCode">
              <j-popup
                v-model="formData.ownerCode"
                org-fields="owner_code,owner_name,owner_type,owner_trade,id_card"
                dest-fields="ownerCode,ownerName,ownerType,ownerTrade,idCard"
                field="ownerCode"
                code="v_xy_park_owner"
                :trigger-change="true"
                @callback="popCallback"
              />
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24">
            <a-form-model-item label="客户名称" >
              <a-input disabled v-model="owner.ownerName"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" >
            <a-form-model-item label="客户类型">
              <a-radio-group disabled v-model="owner.ownerType">
                <a-radio value="1">个人</a-radio>
                <a-radio value="2">公司</a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" v-if="owner.ownerType === '2'">
            <a-form-model-item label="所属行业" >
              <j-dict-select-tag type="list" disabled v-model="owner.ownerTrade" dictCode="park_customer_trade" placeholder="请选择所属行业"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" v-else>
            <a-form-model-item label="身份证号">
              <a-input disabled v-model="owner.idCard" placeholder="请输入身份证号"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider orientation="left" style="margin-bottom:0px;">选择场地</a-divider>
        <ContractHousesItemsTable :dataSource="formData.xyParkContractHouses" ref="ContractHousesItemsTable" />
      </a-form-model>

      <!-- 费项信息 -->
      <div v-show="currentSteps === 1" style="width:100%;">
        <a-form-model layout="horizontal" labelAlign="right" ref="ruleForm2" :label-col="labelCol" :wrapper-col="wrapperCol" :model="formData" :rules="rules">
          <a-row :gutter="24">
            <a-col :xl="8" :lg="8" :md="8" :sm="24" >
              <a-form-model-item label="合同期限" prop="startDate">
                <a-range-picker v-model="term" placeholder="请选择合同期限" style="width:100%;" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <h3 v-show="currentSteps === 1" style="font-weight: bold;margin-top:20px;">付款计划</h3>
        <ContractCostItemsTable style="width:100%;" ref="ContractCostItemsTable" :dataSource="formData.xyParkContractFees" />
      </div>
    </div>
  </j-modal>
</template>
<script>
import { postAction, putAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import moment from 'moment'
import ContractHousesItemsTable from '../modules/ContractHousesItemsTable'
import ContractCostItemsTable from '../modules/ContractCostItemsTable'
import JSelectMultiUser from '@/components/jeecgbiz/JSelectMultiUser'
import { getSn } from '@/api/api'
export default {
  name: 'ContractModal',
  components: {
    ContractHousesItemsTable,
    JSelectMultiUser,
    ContractCostItemsTable
  },
  data() {
    return {
      editModalVisible: false,
      disableSubmit: false,
      fullscreen: true,
      switchFullscreen: true,
      currentSteps: 0,
      title: '合同管理',
      syncLoading: false,
      url: {
        add: '/community/contract/add',
        edit: '/community/contract/edit'
      },
      rules: {
        contractCode: [
          { required: true, message: '请输入合同编码', trigger: 'blur' },
          { validator: (rule, value, callback) => validateDuplicateValue('xy_park_contract', 'contract_code', value, this.formData.id, callback) }
        ],
        contractType: [
          { required: true, message: '请选择合同类型', trigger: 'blur' }
        ],
        bizUser: [
          { required: true, message: '请输入公司', trigger: 'blur' }
        ],
        contractDate: [
          { required: true, message: '请选择签发人', trigger: 'change' }
        ],
        ownerCode: [
          { required: true, message: '请选择乙方', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '请选择合同期限', trigger: 'change' }
        ]
      },
      formData: {},
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      snCode: {
        '1': 'XYCYYXS-${YYYY}-##',
        '2': 'XYJYWY-${YYYY}-###',
        '3': 'XYCYYZL-${YYYY}-###'
      },
      owner: {}
    }
  },
  computed: {
    term: {
      get: function() { // 获取值
        return [this.formData.startDate, this.formData.endDate]
      },
      set: function(val) { // 赋值
        this.formData.startDate = val[0]
        this.formData.endDate = val[1]
      }
    }
  },
  methods: {
    handleCancleDbSync() {
      this.close()
    },
    close() {
      this.currentSteps = 0
      this.disableSubmit = false
      this.$refs['ruleForm'].resetFields()
      this.editModalVisible = false
    },
    getCode(value) {
      getSn(this.snCode[value], {}).then(res => {
        if (res.success) {
          this.formData.contractCode = res.result
        }
      })
    },
    add(type) {
      this.formData = {
        contractType: type,
        contractCode: '',
        endDate: '',
        startDate: '',
        contractStatus: '1',
        xyParkAccount: {}
      }
      this.owner = {}
      this.getCode(type)
      this.editModalVisible = true
    },
    edit(data) {
      this.formData = JSON.parse(JSON.stringify(data))
      this.owner = this.formData.xyParkOwner || {}
      this.editModalVisible = true
    },
    async handleDbSync() {
      Promise.all([
        this.$refs.ContractCostItemsTable.fullValidate(),
        this.$refs['ruleForm'].validate(),
        this.$refs['ruleForm2'].validate()
      ]).then((res) => {
        this.updateData()
      }).catch(function(reason) {
        console.log(reason)
      })
    },
    updateData() {
      this.syncLoading = true
      const house = this.$refs.ContractHousesItemsTable.getTableData()
      this.formData.xyParkContractHouses = house.fullData
      const cost = this.$refs.ContractCostItemsTable.getTableData()
      this.formData.xyParkContractFees = []
      cost.fullData.forEach(item => {
        this.formData.xyParkContractFees.push({
          houseCode: item.houseCode,
          projectName: item.projectName,
          buildingName: item.buildingName,
          floor: item.floor,
          buildingArea: item.buildingArea,
          propertyArea: item.propertyArea
        })
      })
      this.formData.xyParkContractFees = []
      cost.tableData.forEach(item => {
        item.startDate = moment(item.startDate).format('YYYY-MM-DD')
        item.endDate = moment(item.endDate).format('YYYY-MM-DD')
        item.collectionDate = moment(item.collectionDate).format('YYYY-MM-DD')
        this.formData.xyParkContractFees.push(item)
      })
      // this.formData.xyParkContractFees = cost.tableData
      if (this.formData.id) {
        putAction(this.url.edit, this.formData).then(res => {
          this.actionSuccess(res)
          this.close()
        })
      } else {
        postAction(this.url.add, this.formData).then(res => {
          this.actionSuccess(res)
          this.close()
        })
      }
    },
    actionSuccess(res) {
      this.syncLoading = false
      if (res.success) {
        this.$emit('ok')
        this.editModalVisible = false
      } else {
        this.$message.warning(res.message)
      }
    },
    handlePre() {
      if (this.currentSteps === 0) {
        this.$refs['ruleForm'].validate(validate => {
          if (validate) {
            const house = this.$refs.ContractHousesItemsTable.getTableData()
            if (!house.fullData.length) {
              return this.$message.warning('请选择房源')
            }
            ++this.currentSteps
          }
        })
      } else {
        --this.currentSteps
      }
    },
    popCallback(row) {
      this.formData.ownerCode = row.ownerCode
      this.owner = row
    },
    popCallbackAccount(row) {
      this.formData.account = row.account
      this.formData.xyParkAccount = row
    }
  }
}
</script>
<style lang="less">

</style>
